package cn.hiapi.core.basic.sharding.config;

import lombok.Getter;
import org.apache.commons.lang3.ClassUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

/**
 * @author AdinZ
 * @date 2023/12/20 14:26
 */
public class ShardingTableScan {


    private final PathMatchingResourcePatternResolver resourcePatternResolver;
    private final CachingMetadataReaderFactory metadataReaderFactory;
    private final Class<?> clazz;
    @Getter
    private final List<Class<?>> tableClass = new ArrayList<>();

    public ShardingTableScan(Class<?> clazz, String packageName) throws Exception {
        this.clazz = clazz;
        this.resourcePatternResolver = new PathMatchingResourcePatternResolver();
        this.metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + packageName + "/**/*.class";// .concat("/**/*.class");
        this.doRun(packageSearchPath);

    }

    private List<Class<?>> getSuperClass(Class<?> clazz) {
        List<Class<?>> list = new ArrayList<>();
        while (clazz.getSuperclass() != null) {
            list.add(clazz.getSuperclass());
            clazz = clazz.getSuperclass();
        }
        return list;
    }


    private void doRun(String path) throws Exception {
        Resource[] resources = resourcePatternResolver.getResources(path);
        for (Resource resource : resources) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            Class<?> clazz = ClassUtils.getClass(metadataReader.getClassMetadata().getClassName());
            List<Class<?>> superClass = this.getSuperClass(clazz);
            if (superClass.contains(this.clazz)) {
                this.tableClass.add(clazz);
            }
        }
    }


    public static  <T> T newInstance(Class<?> clazz) throws Exception {
        Constructor<?> constructor = clazz.getConstructor();
        return (T) constructor.newInstance();
    }





}
